import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Switch,
  Redirect
} from 'react-router-dom';
import { connect } from 'react-redux'  //引入连接器
import * as userActions from './store/actions/userAction'
import { bindActionCreators } from 'redux';

import Routers from './routes/routerMap'
import NotFound from './pages/NotFound'


function App(props) {
  let { token } = props
  // console.log('token:', token)
  return (
    <div>
      {
        <Router>
          <Switch>
            {
              Routers.map((item, index) => {
                return <Route key={index} path={item.path} exact render={props =>
                  (!item.auth ? (<item.component {...props} />) : (token ? <item.component {...props} /> : <Redirect to={{ pathname: '/login', state: { from: props.location }}} />)
                )} />
              })
            }
            {/* 所有错误路由跳转页面 */}
            <Route component={NotFound} />
          </Switch>
        </Router>
      }
    </div>
  );
}

const mapStateToProps = state => {
  console.log(state)
  return {
    token: state.user.token,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    userActions: bindActionCreators(userActions, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App)
